extends CharacterBody2D

@export var move_speed : float
@export var animated : AnimatedSprite2D
@export var bullet_scene: PackedScene
@export var audio:AudioStreamPlayer2D

var is_game_over: bool = false

func _process(delta: float) -> void:
	if velocity == Vector2.ZERO or is_game_over:
		$playerAudioStreamPlayer2D.stop()
	elif not $playerAudioStreamPlayer2D.playing:
		$playerAudioStreamPlayer2D.play()

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _physics_process(delta: float) -> void:
	if not is_game_over:
		velocity = Input.get_vector("left","right","up","down")*move_speed
		if velocity ==Vector2.ZERO:
			animated.play("idle")
		else:  
			animated.play("run") 
		move_and_slide()
	else :
		animated.play("die")
	
func game_over():
	if not is_game_over:
		is_game_over = true
		$gameoverAudioStreamPlayer2D.play()
		$reload.start()
		get_tree().current_scene.show_game_over()
	


func _on_timer_timeout() -> void:
	if velocity ==Vector2.ZERO and not is_game_over:
		var bullet_node = bullet_scene.instantiate()
		bullet_node.position = position + Vector2(15,7)
		$bulletAudioStreamPlayer2D.play()
		get_tree().current_scene.add_child(bullet_node)
		


func _on_reload_timeout() -> void:
		get_tree().reload_current_scene()
